<template>
  <!-- 相关方单位名录 -->
  <div class="relatedparty">
    <basic-container>
      <avue-crud
        :option="option"
        :table-loading="loading"
        :data="data"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        v-model="form"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @selection-change="selectionChange"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
        @on-load="onLoad"
      >

        <!-- 左上方菜单栏 -->
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            v-if="permission.relatedparty_delete"
            @click="handleDelete">
            删 除
          </el-button>
          <el-button
            type="warning"
            size="small"
            plain
            @click="addBlackList">
            加入黑名单
          </el-button>
          <el-button
            type="success"
            size="small"
            plain
            @click="removeBlackList">
            移除黑名单
          </el-button>
        </template>

        <!-- 营业执照表单自定义 -->
        <template slot="yyzzForm">
          <div class="yyzz_content">
            <el-upload
              v-if="dialogType !== 'view'"
              accept="image/*"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="yyzzFileList"
              :before-upload="beforeUploadYYZZ"
              :on-success="uploadYYZZSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-picture">选择图片</el-button>
            </el-upload>

            <el-tag
              v-for="(item, index) in yyzzFileList"
              :key="index"
              type="info"
              :closable="dialogType !== 'view'"
              @close="handleRemoveYYZZ(index)"
            >
              <img
                :src="item.response.data.fileUrl"
                @click="previewYYZZ(item)"
                alt
              />
            </el-tag>
          </div>
        </template>

        <!-- 资质证书表单自定义 -->
        <template slot="cbszzzsForm">
          <div class="zzzs_content">
            <el-upload
              v-if="dialogType !== 'view'"
              accept="image/*"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="zzzsFileList"
              :before-upload="beforeUploadZZZS"
              :on-success="uploadZZZSSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-picture">选择图片</el-button>
            </el-upload>

            <el-tag
              v-for="(item, index) in zzzsFileList"
              :key="index"
              type="info"
              :closable="dialogType !== 'view'"
              @close="handleRemoveZZZS(index)"
            >
              <img
                :src="item.response.data.fileUrl"
                @click="previewZZZS(item)"
                alt
              />
            </el-tag>
          </div>
        </template>

        <!-- 附件表单自定义 -->
        <template slot="fjForm">
          <div>
            <el-upload
              v-if="dialogType !== 'view'"
              action="/api/fileManager/upload/file"
              :headers="SetHeaders"
              :file-list="fjFileList"
              :before-upload="beforeUploadFJ"
              :on-remove="handleRemoveFJ"
              :on-success="uploadFJSuccess"
            >
              <el-button size="small" type="primary" icon="el-icon-document">选择文件</el-button>
            </el-upload>

            <a
              v-else
              v-for="(item, index) in fjFileList"
              :key="index"
              :href="downloadHead + item.response.data.id"
              style="color:#409EFF"
            >
              <i class="el-icon-download" style="margin-right:5px;"></i>下载文件（{{ item.name }}）
            </a>
          </div>
        </template>

        <!-- 状态表格自定义 -->
        <template slot="spzt" slot-scope="scope">
          <span v-if="approveStatus[scope.row['spzt']] === undefined">-</span>
          <span v-else>{{approveStatus[scope.row['spzt']]}}</span>
        </template>

        <!-- 审批表格自定义 -->
        <template slot="approve" slot-scope="scope">
          <el-button
            v-if="scope.row['approvalSetButton'] === 1"
            type="danger"
            size="mini"
            icon="el-icon-setting"
            @click="handleApproveSetting(scope.row)">
            审批设置
          </el-button>
          <el-button
            v-if="scope.row['approvalButton'] === 1"
            type="success"
            size="mini"
            icon="el-icon-document-checked"
            @click="handleApprove(scope.row)">
            审批
          </el-button>
          <span v-if="scope.row['approvalSetButton'] === 0 && scope.row['approvalButton'] === 0">-</span>
        </template>

        <!-- 关联表格自定义 -->
        <template slot="relation" slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="handleRelation(scope.row)">
            添加关联信息
          </el-button>
        </template>

      </avue-crud>

      <!-- 弹窗：添加关联信息 -->
      <el-dialog 
        title="添加关联信息"
        append-to-body
        :visible.sync="addRelationDialog"
        :close-on-click-modal="false" 
        :before-close="closeAddRelationDialog"
        width="60%"
        class="add_relation_dialog"
      >

        <!-- 内容 -->
        <el-tabs v-model="activeRelationModal" type="card" @tab-click="changeRelationModal">

          <!-- 资质信息表 -->
          <el-tab-pane label="资质信息表" :name="qualificationStr">
            <relatedpartyqualifications
              :addRelationDialog="addRelationDialog"
              :xgfdwId="xgfdwId">
            </relatedpartyqualifications>
          </el-tab-pane>

          <!-- 作业人员表 -->
          <el-tab-pane label="作业人员表" :name="staffStr">
            <relatedpartystaff
              :addRelationDialog="addRelationDialog"
              :xgfdwId="xgfdwId">
            </relatedpartystaff>
          </el-tab-pane>
        </el-tabs>

        <!-- 按钮 -->
        <div class="add_relation_footer">
          <el-button 
            type="primary"
            size="small"
            @click="closeAddRelationDialog()">
            关 闭
          </el-button>
        </div>

      </el-dialog>

      <!-- 弹窗：图片 -->
      <viewpicture
        :localPicBox="localPicBox"
        :localPictures="localPictures"
        :viewPicTitle="viewPicTitle"
        @confirmViewPicture="confirmViewPicture"
        @handleClosePicBox="handleClosePicBox">
      </viewpicture>

      <!-- 弹窗：审批设置 -->
      <approveSetting
        :approveSettingDialog="approveSettingDialog"
        :selectedSettingId="selectedSettingId"
        @confirmApproveSetting="confirmApproveSetting"
        @closeApproveSettingDialog="closeApproveSettingDialog">
      </approveSetting>

      <!-- 审批弹窗 -->
      <approvalRelatedParty
        :approveDialog="approveDialog"
        :approvePartyId="approvePartyId"
        @confirmApproveRelatedParty="confirmApproveRelatedParty"
        @closeApproveDialog="closeApproveDialog">
      </approvalRelatedParty>

    </basic-container>
  </div>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  blacklist,
  setApproveUser
} from "@/api/basedata/interestedpartymange/relatedparty";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import viewpicture from "../../saferisk/components/viewpicture.vue";
import relatedpartyqualifications from "./relatedpartyqualifications.vue";
import relatedpartystaff from "./relatedpartystaff.vue";
import approveSetting from "./components/approveSetting";
import approvalRelatedParty from "./components/approvalRelatedParty.vue";

export default {
  components: {
    viewpicture,
    relatedpartyqualifications,
    relatedpartystaff,
    approveSetting,
    approvalRelatedParty
  },
  data() {
    return {
      // 弹窗：查看图片
      localPicBox: false,
      localPictures: [],
      viewPicTitle: "",
      // 列表
      approveStatus: {
        1: "待审批",
        2: "审批中",
        3: "审批不通过",
        4: "审批完成"
      },
      form: {},
      query: {},
      data: [],
      loading: true,
      selectionList: [],
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchSpan: 5,
        searchMenuSpan: 4,
        border: true,
        index: false,
        selection: true,
        viewBtn: true,
        refreshBtn: true,
        columnBtn: false,
        dialogClickModal: false,
        menuWidth: 200,
        column: [
          {
            label: "单位名称",
            prop: "dwmc",
            align: "center",
            rules: [{
              required: true,
              message: "请输入单位名称",
              trigger: "blur"
            }]
          },
          {
            label: "单位性质",
            prop: "dwxz",
            hide: true
          },
          {
            label: "单位类别",
            prop: "cbxlb",
            align: "center",
            width: 120,
            search: true,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=contractor_category",
            props: {
              label: "dictValue",
              value: "dictKey",
            }
          },
          {
            label: "作业类型",
            prop: "cbslx",
            align: "center",
            search: true,
            width: 120,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=type_of_contractor",
            props: {
              label: "dictValue",
              value: "dictKey",
            }
          },
          {
            label: "资格证书编号",
            prop: "zgzsbh",
            hide: true
          },
          {
            label: "资质证书到期日期",
            prop: "zgzsdqrq",
            hide: true,
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd"
          },
          {
            label: "承包商电话",
            prop: "cbsdh",
            hide: true
          },
          {
            label: "邮箱",
            prop: "yx",
            hide: true
          },
          {
            label: "联系人",
            prop: "xlr",
            align: "center"
          },
          {
            label: "是否列入黑名单",
            prop: "sflrhmd",
            align: "center",
            width: 130,
            display: false,
            type: "select",
            dicData: [{
              label: "否",
              value: 0
            }, {
              label: "是",
              value: 1
            }],
          },
          {
            label: "法人代表",
            prop: "frdb",
            hide: true
          },
          {
            label: "联系电话",
            prop: "lxdh",
            hide: true
          },
          {
            label: "经营范围",
            prop: "jyfw",
            hide: true,
            type: "textarea",
            span: 24,
            maxlength: 150,
          },
          {
            label: "营业执照",
            prop: "yyzz",
            hide: true,
            formslot: true
          },
          {
            label: "资质证书",
            prop: "cbszzzs",
            hide: true,
            formslot: true
          },
          {
            label: "附件",
            prop: "fj",
            hide: true,
            formslot: true
          },
          {
            label: "状态",
            prop: "spzt",
            align: "center",
            display: false,
            width: 120,
            slot: true
          },
          {
            label: "审批",
            prop: "approve",
            align: "center",
            width: 220,
            slot: true,
            display: false
          },
          {
            label: "关联",
            prop: "relation",
            align: "center",
            slot: true,
            display: false,
            width: 160
          }
        ]
      },
      // 营业执照
      dialogType: "",
      downloadHead: "/api/fileManager/download/",
      yyzzFileList: [],
      SetHeaders: { "Blade-Auth": getToken() },
      // 资质证书
      zzzsFileList: [],
      // 附件
      fjFileList: [],
      // 弹窗：关联信息
      addRelationDialog: false,
      activeRelationModal: "",
      qualificationStr: "qualification",
      staffStr: "staff",
      xgfdwId: "",
      // 弹窗：审批设置
      approveSettingDialog: false,
      selectedSettingId: "",
      // 弹窗：审批
      approveDialog: false,
      approvePartyId: ""
    };
  },
  computed: {
    ...mapGetters(["permission"]),

    // 按钮权限
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.relatedparty_add, false),
        viewBtn: this.vaildData(this.permission.relatedparty_view, false),
        delBtn: this.vaildData(this.permission.relatedparty_delete, false),
        editBtn: this.vaildData(this.permission.relatedparty_edit, false)
      };
    },

    // 勾选项ID
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {

    // 加入黑名单
    addBlackList() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一个单位!");
        return;
      }
      this.$confirm("确定将选择单位加入黑名单?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return blacklist(this.ids, 1);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    // 移出黑名单
    removeBlackList() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一个单位!");
        return;
      }
      this.$confirm("确定将选择单位移出黑名单?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return blacklist(this.ids, 0);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    // 新增
    rowSave(row, done, loading) {
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          window.console.log(error);
        }
      );
    },

    // 修改
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        },
        error => {
          loading();
          console.log(error);
        }
      );
    },

    // 删除一条
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },

    // 删除多条
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },

    // 打开新增、编辑、查看弹窗前
    beforeOpen(done, type) {
      if(type === "edit" && this.form.editButton === 0) {
        this.$message.warning("当前相关方单位不可编辑!");
        return;
      }
      this.dialogType = type;
      this.yyzzFileList = [];
      this.zzzsFileList = [];
      this.fjFileList = [];
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          if (this.form.yyzz && this.form.yyzzFile && JSON.stringify(this.form.yyzzFile) !== "{}") {
            this.yyzzFileList.push({
              name: this.form.yyzzFile.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: this.form.yyzzFile
              }
            });
          }
          if (this.form.cbszzzs && this.form.cbszzzsFile && JSON.stringify(this.form.cbszzzsFile) !== "{}") {
            this.zzzsFileList.push({
              name: this.form.cbszzzsFile.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: this.form.cbszzzsFile
              }
            });
          }
          if (this.form.fj && this.form.fjFile && JSON.stringify(this.form.fjFile) !== "{}") {
            this.fjFileList.push({
              name: this.form.fjFile.fileName,
              response: {
                code: 200,
                msg: "操作成功",
                success: true,
                data: this.form.fjFile
              }
            });
          }
        });
      }
      done();
    },

    // 清空搜索条件
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    // 搜索条件改变
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },

    // 勾选
    selectionChange(list) {
      this.selectionList = list;
    },

    // 清空勾选
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },

    // 更换页数
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },

    // 更换每页显示数量
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },

    // 刷新
    refreshChange() {
      this.onLoad(this.page, this.query);
    },

    // 加载数据
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query)
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    /**
     * 上传营业执照
     */

    // 上传营业执照前
    beforeUploadYYZZ(file) {
      console.log(file);
      var isLimit = this.yyzzFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一张图片!");
      }
      return isLimit;
    },

    // 上传营业执照成功
    uploadYYZZSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.yyzzFileList = fileList;
      this.form.yyzz = this.formatFJ(this.yyzzFileList);
    },

    // 删除营业执照
    handleRemoveYYZZ(index) {
      this.yyzzFileList.splice(index, 1);
      this.form.yyzz = this.formatFJ(this.yyzzFileList);
    },

    // 格式化附件ID
    formatFJ(fileList) {
      var ids = [];
      fileList.forEach(item => {
        ids.push(item.response.data.id);
      });
      return ids.join(",");
    },

    /**
     * 上传资质证书
     */

    // 上传资质证书前
    beforeUploadZZZS(file) {
      console.log(file);
      var isLimit = this.zzzsFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一张图片!");
      }
      return isLimit;
    },

    // 上传资质证书成功
    uploadZZZSSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.zzzsFileList = fileList;
      this.form.cbszzzs = this.formatFJ(this.zzzsFileList);
    },

    // 删除资质证书
    handleRemoveZZZS(index) {
      this.zzzsFileList.splice(index, 1);
      this.form.cbszzzs = this.formatFJ(this.zzzsFileList);
    },

    /**
     * 上传附件
     */

    // 上传附件前
    beforeUploadFJ(file) {
      console.log(file);
      var isLimit = this.fjFileList.length + 1 <= 1;
      if (!isLimit) {
        this.$message.warning("只能选择一个附件!");
      }
      return isLimit;
    },

    // 上传附件成功
    uploadFJSuccess(response, file, fileList) {
      if (response.code !== 200 || response.success !== true) {
        return;
      }
      this.fjFileList = fileList;
      this.form.fj = this.formatFJ(this.fjFileList);
    },

    // 删除附件
    handleRemoveFJ(file, fileList) {
      this.fjFileList = fileList;
      this.form.fj = this.formatFJ(this.fjFileList);
    },

    /**
     * 弹窗：图片
     */

    // 点击营业执照列表中已上传的图片
    previewYYZZ(file) {
      if (
        file.response &&
        file.response.code === 200 &&
        file.response.data &&
        file.response.data.fileUrl
      ) {
        this.localPictures = [file.response.data];
        this.localPicBox = true;
        this.viewPicTitle = "营业执照";
      }
    },

    // 点击资质证书列表中已上传的图片
    previewZZZS(file) {
      if (
        file.response &&
        file.response.code === 200 &&
        file.response.data &&
        file.response.data.fileUrl
      ) {
        this.localPictures = [file.response.data];
        this.localPicBox = true;
        this.viewPicTitle = "承包商资质证书";
      }
    },

    // 确认照片
    confirmViewPicture() {
      this.localPictures = [];
      this.localPicBox = false;
      this.viewPicTitle = "";
    },

    // 关闭弹窗
    handleClosePicBox() {
      this.confirmViewPicture();
    },

    /**
     * 弹窗：添加关联信息
    */

    // 打开关联信息弹窗
    handleRelation(row) {
      this.activeRelationModal = this.qualificationStr;
      this.addRelationDialog = true;
      this.xgfdwId = row.id;
    },

    // 关闭、取消关联信息弹窗
    closeAddRelationDialog() {
      this.activeRelationModal = "";
      this.addRelationDialog = false;
      this.xgfdwId = "";
    },

    /**
     * 弹窗：审批设置
    */

    // 打开审批设置弹窗
    handleApproveSetting(row) {
      this.selectedSettingId = row.id;
      this.approveSettingDialog = true;
    },

    // 确定审批设置
    confirmApproveSetting(approvalUsers) {
      var updateData = this.formatSettingData(approvalUsers);
      setApproveUser(updateData).then(res => {
        if(res.data.success) {
          this.closeApproveSettingDialog();
          this.page.currentPage = 1;
          this.onLoad(this.page);
        }
      });
    },

    // 格式化审批设置数据
    formatSettingData(row) {
      var data = {
        bizId: this.selectedSettingId,
        flowOperatorList: []
      };
      for(let i = 0 ; i < row.length ; i++) {
        data.flowOperatorList.push({
          userId: row[i].id,
          taskOrder: i + 1
        });
      }
      return data;
    },

    // 关闭、取消审批设置弹窗
    closeApproveSettingDialog() {
      this.selectedSettingId = "";
      this.approveSettingDialog = false;
    },

    /**
     * 弹窗：审批
    */

    // 打开审批弹窗
    handleApprove(row) {
      this.approvePartyId = row.id;
      this.approveDialog = true;
    },

    // 关闭、取消审批弹窗
    closeApproveDialog() {
      this.approvePartyId = "";
      this.approveDialog = false;
    },

    // 确认审批
    confirmApproveRelatedParty() {
      this.closeApproveDialog();
      this.page.currentPage = 1;
      this.onLoad(this.page);
    }

  }
};
</script>

<style lang="scss">
.yyzz_content,
.zzzs_content {
  .el-upload-list {
    display: none;
  }

  .el-tag {
    .el-icon-close {
      top: -84px;
    }
  }
}

.approve_setting_dialog,
.choose_approve_user_dialog {
  .avue-crud__menu,
  .avue-crud__pagination {
    display: none !important;
  }
}

.approve_setting_dialog {
  .el-table__header-wrapper,
  .el-table__empty-block {
    display: none !important;
  }
}

.related_party_approve_dialog {
  .avue-form__menu--center {
    text-align: center;
  }
}

.add_relation_dialog {
  .avue-crud__menu {
    display: flex !important;
  }

  .avue-crud__pagination {
    display: block !important;
  }
}
</style>

<style lang="scss" scoped>
.yyzz_content,
.zzzs_content {
  .el-upload-list__item {
    display: none !important;
  }

  .el-tag {
    height: 100px;
    line-height: 100px;
    padding: 0px 10px 0px 0px;
    margin-left: 0px;
    margin-top: 10px;
  }

  img {
    width: 98px;
    height: 98px;
    cursor: pointer;
  }
}

.add_relation_footer {
  text-align: center;
  margin-top: 15px;

  .el-button {
    width: 100px;
    height: 35px;
  }
}
</style>